package com.example.rabbitmq01.rpc;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Server {

    private static ConnectionFactory factory;
    private static Connection connection;
    private static Channel channel;

    private static final String QUEUE = "queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接
        factory = new ConnectionFactory();
        connection = factory.newConnection();
        channel = connection.createChannel();

        //创建队列
        channel.queueDeclare(QUEUE, false, false, false, null);

        //接收消息

        //此处需要做的是,对客户端那边的消息计算并响应
        //将响应结果发送到客户端那边的响应回调队列
        channel.basicConsume(QUEUE, true, (consumerTag, delivery) -> {
            //1.接收消息并计算响应
            String message = new String(delivery.getBody());
            int ans = Sum(Integer.parseInt(message));
            //2.将响应发送到回调队列中
            channel.basicPublish("", delivery.getProperties().getReplyTo(), delivery.getProperties(), ("" + ans).getBytes());
        }, (consumerTag) -> {

        });

    }


    private static int Sum(int num) {
        int tmp = 0;
        for(int i = 1; i <= num; i++){
            tmp += i;
        }
        return tmp;
    }
}
